package by.demchenko.sample.webapp.page.home.panel;

import by.demchenko.sample.datamodel.Account;
import by.demchenko.sample.webapp.page.home.share.CreateAccountPage;
import org.apache.wicket.Application;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.bean.validation.PropertyValidator;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.util.string.Strings;

public class LoginForm extends Panel {

    private String username;
    private String password;

    public LoginForm(String id) {
        super(id);


    }

    @Override
    protected void onInitialize() {
        super.onInitialize();

        Form<Account> form = new Form<>("form");

        form.setDefaultModel(new CompoundPropertyModel<LoginForm>(this));

        add(new FeedbackPanel("feedback"));

        final TextField<String> tfLogin = new TextField<>("username");
        tfLogin.add(new PropertyValidator<>());
        tfLogin.setLabel(new ResourceModel("person.login"));
        tfLogin.add(new AttributeModifier("placeholder", getString("person.login")));
        form.add(tfLogin);

        final PasswordTextField tfPassword = new PasswordTextField("password");
        tfPassword.add(new PropertyValidator<>());
        tfPassword.setLabel(new ResourceModel("person.password"));
        tfPassword.add(new AttributeModifier("placeholder", getString("person.password")));
        form.add(tfPassword);

        form.add(new SubmitLink("sumbit-link") {
            @Override
            public void onSubmit() {
                if (Strings.isEmpty(username) || Strings.isEmpty(password)) {
                    return;
                }
                final boolean authResult = AuthenticatedWebSession.get().signIn(username, password);
                if (authResult) {
                    setResponsePage(Application.get().getHomePage());
                } else {
                    error("Ошибка авторизации");
                }
            }

            @Override
            public void onError() {
                super.onError();
            }
        });

        add(form);

        add(new Link("registration") {

            @Override
            public void onClick() {
                setResponsePage(new CreateAccountPage());
            }
        });
    }
}
